package messages.observer;

import state.group.events.BaseEvent;
import state.group.events.EventCollection;
import state.group.events.EventFactory;

import messages.BaseMessage;
import messages.ByteList;
import messages.MessageType;

public class EventCollectionMessage extends BaseMessage {
    
    private byte[] data = null;
    private EventCollection deserializedEvents = null;

    public EventCollectionMessage(byte[] data)
    {
        super(data);
        
        this.data = data;
    }
    
    public EventCollectionMessage(EventCollection events)
    {
        super(null);
        
        ByteList list = new ByteList();
        
        list.addByte(getMessageType().getIdentifier());
        
        for (BaseEvent e : events)
        {
            e.appendToByteList(list);
        }
        
        this.data = list.toByteArray();
        
    }

    @Override
    public byte[] toByteArray()
    {
        return data;
    }

    @Override
    public MessageType getMessageType()
    {
        return MessageType.EventCollectionMessage;
    }
    
    public EventCollection getEvents()
    {
        if (deserializedEvents != null)
        {
            return deserializedEvents;
        }
        
        this.deserializedEvents = EventFactory.parseEvents(data, 1);
        
        return deserializedEvents;
    }

    @Override
    public int getMessageSize()
    {
        return -1;
    }
    
}
